package co.com.javeriana.aes.oms.campaigns;

import co.com.javeriana.aes.oms.common.BaseBean;
import co.com.javeriana.aes.oms.common.entity.Campaign;
import co.com.javeriana.aes.oms.common.service.CommonServiceLocal;
import co.com.javeriana.aes.oms.constants.NavRules;
import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author Jonathan Fernandez <jonathan.fvargas@gmail.com>
 */
@ManagedBean(name = "CampaignBean")
@RequestScoped
public class CampaignBean extends BaseBean implements java.io.Serializable{

    @EJB
    private CommonServiceLocal localService;
    private Campaign campaign = new Campaign();
    private Campaign selected;
    private UploadedFile file;
    private List<Campaign> dtos;

    @PostConstruct
    public void init() {
        dtos = localService.getCampaigns();
    }

    public StreamedContent getImage() {

        FacesContext context = FacesContext.getCurrentInstance();

        if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            // So, we're rendering the view. Return a stub StreamedContent so that it will generate right URL.
            return new DefaultStreamedContent();
        } else {
            // So, browser is requesting the image. Return a real StreamedContent with the image bytes.
            String id = context.getExternalContext().getRequestParameterMap().get("id");
            Campaign c = null;
            try {
                c = localService.getCampaign(Long.valueOf(id));
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            return new DefaultStreamedContent(new ByteArrayInputStream(c.getImage()));
        }
    }

    public Campaign getSelected() {
        return selected;
    }

    public void setSelected(Campaign selected) {
        this.selected = selected;
    }

    public List<Campaign> getDtos() {
        return dtos;
    }

    public void setDtos(List<Campaign> dtos) {
        this.dtos = dtos;
    }

    public CommonServiceLocal getLocalService() {
        return localService;
    }

    public void setLocalService(CommonServiceLocal localService) {
        this.localService = localService;
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public Campaign getCampaign() {
        return campaign;
    }

    public void setCampaign(Campaign campaign) {
        this.campaign = campaign;
    }

    private void resetValues() {
        campaign = new Campaign();
    }

    public String cancelButton() {
        return NavRules.GO_TO_HOME.name();
    }

    public void saveButton() {

        try {

            if (file != null) {
                //manual set ID, Oracle makes the ++
                campaign.setId(new Long(1));
                campaign.setImage(file.getContents());
                Random rn = new Random();
                int min =1;
                int max =1000000;
                long answer = rn.nextInt(max - min + 1) + min;
                campaign.setProductId(answer);
                //calling service                
                localService.createCampaign(campaign);
                resetValues();
                addMessage("Campaña creada con éxito");
            } else {
                addMessage("Error creando campaña");
            }

        } catch (Exception ex) {
            addMessage("Error creando campaña");
            Logger.getLogger(CampaignBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String deleteEvent() {
        try {
            //delete object
            localService.deleteCampaign(selected);
            addMessage("Campaña eliminada con éxito");
        } catch (Exception ex) {
            addMessage("Error al eliminar campaña");
            ex.printStackTrace();
        }
        return null;
    }    

}
